package com.fdb.efp.nls.service.impl.psd.apply;

import com.fdb.efp.nls.service.facade.NlsApplyInfoService;
import com.fdb.efp.nls.service.facade.NlsQueueSoltComnService;
import com.fdb.efp.nls.service.facade.UpdateLmtPrdContService;
import com.fdb.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.fdb.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import com.fdb.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import com.fdb.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.fdb.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.basic.framework.core.exception.ESBException;
import com.fdb.basic.framework.core.exception.QueuePauseException;
import com.fdb.efp.esb.common.constant.ESBClientConstance;
import com.fdb.efp.esb.service.bo.req.psd.PsdApplyApprReqBean;
import com.fdb.efp.esb.service.facade.EsbInvokeWrapper;
import com.fdb.efp.esb.service.facade.psd.PsdApplyApprService;
import com.fdb.efp.limit.service.facade.LmtPrdContService;
import com.fdb.efp.limit.service.vo.LmtPrdContVO;
import com.fdb.efp.nls.service.impl.SoltServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.fdb.efp.nls.common.ConsoleConstant.LIMIT_STS_02;

/**
 * 需求编号:
 * 问题编号:
 * 开发人员: ludayong
 * 创建日期:2019/9/7
 * 功能描述:
 * 修改日期:2019/9/7
 * 修改描述:
 */
@Service("psdApplyAccessService")
public class PsdApplyAccessServiceImpl extends SoltServiceImpl implements FrameworkService {

	@Override
	protected void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {

		String applySeq = nlsApplyInfoVO.getApplySeq();
		logger.info("======>普税贷用信审批服务开始,流水号" + applySeq + "<======");
		try {
			NlsApplyInfoVO queryNlsApplyInfoVO = new NlsApplyInfoVO();
			queryNlsApplyInfoVO.setApplySeq(applySeq);
			queryNlsApplyInfoVO = Optional.ofNullable(nlsApplyInfoService.queryByPk(queryNlsApplyInfoVO))
					.orElseThrow(() -> new BizException("普税贷通过 " + applySeq + "流水号查询不到用信信息!!!"));

			NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
			Objects.requireNonNull(nlsCreditInfoVO, "普税贷授信审批服务获取到的授信信息为空");

			PreNlsCreditInfoVO preNlsCreditInfoVO = new PreNlsCreditInfoVO();
			preNlsCreditInfoVO.setApplySeq(nlsCreditInfoVO.getPreLmtApplySeq());
			preNlsCreditInfoVO = preNlsCreditInfoService.queryByPk(preNlsCreditInfoVO);

			Objects.requireNonNull(preNlsCreditInfoVO, "普税贷授信审批服务获取到的预授信信息为空");
			Objects.requireNonNull(nlsCreditInfoVO.getApproveRateY(), "获取到的审批年利率为空");

			// 调用用信审批接口三次
			invokeApplyInterface(nlsApplyInfoVO, applySeq, nlsCreditInfoVO, preNlsCreditInfoVO);
			throw new QueuePauseException("");

		} catch (Exception e) {
			logger.error("======>普税贷【用信审批服务】执行失败原因为<======", e.getMessage());
			if (!(e instanceof QueuePauseException)) {
				updateLmtPrdContService.recoverLmtPro(nlsApplyInfoVO.getLmtApplySeq(),nlsApplyInfoVO.getApplySeq());
			}
			nlsProcessBizVo.setExceptionFlag(Boolean.TRUE);
			nlsProcessBizVo.setRefuseMsg(e.getMessage());
			nlsProcessBizVo.setExceptionMsg(e);
		} finally {
			logger.info("======>普税贷用信审批服务结束,流水号<======" + applySeq);
		}
	}

	private void invokeApplyInterface(NlsApplyInfoVO nlsApplyInfoVO, String applySeq, NlsCreditInfoVO nlsCreditInfoVO, PreNlsCreditInfoVO preNlsCreditInfoVO) throws ESBException, InterruptedException {
		PsdApplyApprReqBean psdApplyApprReqArray = new PsdApplyApprReqBean();
		PsdApplyApprReqBean.QryRptsInfArry psdApplyApprReqBean = new PsdApplyApprReqBean.QryRptsInfArry();
		psdApplyApprReqBean.setAppNo(applySeq);
		psdApplyApprReqBean.setLPRprsIdentNo(nlsApplyInfoVO.getCertCode());
		psdApplyApprReqBean.setLPMblNo(nlsApplyInfoVO.getMobile());
		psdApplyApprReqBean.setLPNm(nlsApplyInfoVO.getCusName());
		psdApplyApprReqBean.setLPIdentTp(nlsApplyInfoVO.getCertType());
		psdApplyApprReqBean.setUsrID(ESBClientConstance.CnsmrSysNo);
		psdApplyApprReqBean.setDeptNo(nlsApplyInfoVO.getNlsOperOrgid());
		psdApplyApprReqBean.setTaxpyrIdntfNo(preNlsCreditInfoVO.getTaxIdentificationNumber());
		psdApplyApprReqBean.setEntpLo(preNlsCreditInfoVO.getRegistration());
		psdApplyApprReqBean.setEntpNm(preNlsCreditInfoVO.getEnterpriseName());
		psdApplyApprReqBean.setEntpUSCC(preNlsCreditInfoVO.getSocialCreditCode());
		psdApplyApprReqBean.setUsrID(ESBClientConstance.CnsmrSysNo);
		psdApplyApprReqBean.setDeptNo(nlsCreditInfoVO.getNlsOperOrgid());
		//申请人网贷及个贷已有授信额度:同一个证件号的所有信用担保类型的有效的授信额度之和
		LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
		lmtPrdContVO.setCertType(preNlsCreditInfoVO.getCertType());
		lmtPrdContVO.setCertCode(preNlsCreditInfoVO.getCertNo());
		lmtPrdContVO.setLmtStatus(LIMIT_STS_02);
		lmtPrdContVO.setAssureMeansMain(BaseConstant.ASSURE_MEANS_00);
		List<LmtPrdContVO> lmtPrdContVOS = lmtPrdContService.aplcOCMExstdCrLmt(lmtPrdContVO);
		BigDecimal approveAmtTotal = lmtPrdContVOS.stream().
				map(LmtPrdContVO::getLmtAmt).
				filter(Objects::nonNull).
				reduce(BigDecimal.ZERO, BigDecimal::add);
		psdApplyApprReqBean.setOCMPLSExstdCrLmt(approveAmtTotal.doubleValue());

		psdApplyApprReqBean.setAnulzLoanIntRt(nlsCreditInfoVO.getApproveRateY().doubleValue());

		List<PsdApplyApprReqBean.QryRptsInfArry> qryRptsInfArries = new ArrayList<>();
		qryRptsInfArries.add(psdApplyApprReqBean);
		psdApplyApprReqArray.setQryRptsInfArrys(qryRptsInfArries);
		psdApplyApprReqArray.setGlobaNo(nlsApplyInfoVO.getGlobalSerno());
		EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(psdApplyApprService, psdApplyApprReqArray, nlsQueueSoltComnService);
		esbInvokeWrapper.invoke3Threes();
	}

	/**
	 * 日志信息
	 */
	private final Logger logger = LoggerFactory.getLogger(PsdApplyAccessServiceImpl.class);


	// 告警服务
	@Autowired
	@Qualifier("nlsQueueSoltComnService")
	private NlsQueueSoltComnService nlsQueueSoltComnService;

	// 网贷申请基本信息
	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;

	@Autowired
	@Qualifier("psdApplyApprService")
	private PsdApplyApprService psdApplyApprService;


	@Autowired
	@Qualifier("nlsCreditInfoService")
	private NlsCreditInfoService nlsCreditInfoService;

	@Autowired
	@Qualifier("preNlsCreditInfoService")
	private PreNlsCreditInfoService preNlsCreditInfoService;

	@Autowired
	@Qualifier("lmtPrdContService")
	private LmtPrdContService lmtPrdContService;

	@Autowired
	@Qualifier("updateLmtPrdContService")
	private UpdateLmtPrdContService updateLmtPrdContService;
}
